const Storage = require('../../utils/storage')

Page({
  data: {
    description: '',
    fileList: [],
    selectedTypeIndex: -1,
    typeOptions: [
      { label: '内科', value: 'internal' },
      { label: '外科', value: 'surgery' },
      { label: '妇产科', value: 'gynecology' },
      { label: '儿科', value: 'pediatrics' },
      { label: '皮肤科', value: 'skin' },
      { label: '眼科', value: 'eye' },
      { label: '口腔科', value: 'dental' },
      { label: '其他', value: 'other' }
    ],
    descriptionError: '',
    imageError: '',
    typeError: '',
    showPicker: false,
    selectedType: '',
    selectedTypeValue: '',
    showTypeSelector: false,
    tempSelectedIndex: null,
    gridConfig: {
      column: 3,
      width: 160,
      height: 160
    },
    uploadConfig: {
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    },
    maxImageCount: 3,
    maxImageSize: 10 * 1024 * 1024
  },

  // 问题描述变化
  onDescriptionChange(e) {
    this.setData({
      description: e.detail.value,
      descriptionError: ''
    });
  },

  // 选择图片
  onClickUpload() {
    const remainCount = this.data.maxImageCount - this.data.fileList.length;
    
    if (remainCount <= 0) {
      wx.showToast({
        title: `最多上传${this.data.maxImageCount}张图片`,
        icon: 'none'
      });
      return;
    }

    wx.chooseMedia({
      count: remainCount,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const newFiles = res.tempFiles
          .map(file => {
            if (file.size > this.data.maxImageSize) {
              wx.showToast({
                title: '图片大小不能超过10MB',
                icon: 'none'
              });
              return null;
            }
            
            return {
              url: file.tempFilePath,
              name: file.tempFilePath.split('/').pop(),
              type: 'image',
              size: file.size,
              fileType: file.fileType,
              width: file.width,
              height: file.height
            };
          })
          .filter(file => file !== null);

        if (newFiles.length > 0) {
          this.setData({
            fileList: [...this.data.fileList, ...newFiles],
            imageError: ''
          });
        }
      },
      fail: (error) => {
        if (error.errMsg?.includes('authorize')) {
          wx.showModal({
            title: '提示',
            content: '请授权访问相册和相机',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        } else {
          wx.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 预览图片
  async onPreviewImage(e) {
    const { index } = e.currentTarget.dataset;
    const images = this.data.fileList.map(file => file.url);
    
    if (!images.length) return;

    try {
      await wx.previewMedia({
        sources: this.data.fileList.map(file => ({
          url: file.url,
          type: 'image',
          width: file.width || 0,
          height: file.height || 0
        })),
        current: index
      });
    } catch (error) {
      try {
        await wx.previewImage({
          urls: images,
          current: images[index]
        });
      } catch (previewError) {
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    }
  },

  // 删除图片
  onRemoveImage(e) {
    const { index } = e.detail;
    const fileList = this.data.fileList.slice();
    fileList.splice(index, 1);
    this.setData({ 
      fileList,
      imageError: '' 
    });
  },

  // 图片上传到服务器
  uploadImage(tempFilePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'YOUR_UPLOAD_URL',
        filePath: tempFilePath,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data',
          'Authorization': Storage.getAuthToken()
        },
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
              resolve(data.url);
            } catch (e) {
              reject(new Error('解析响应数据失败'));
            }
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: () => {
          reject(new Error('上传请求失败'));
        }
      });
    });
  },

  // 处理图片上传
  async handleImageUpload() {
    if (this.data.fileList.length === 0) {
      return [];
    }

    try {
      const uploadPromises = this.data.fileList.map(async file => {
        if (file.url.startsWith('http')) {
          return file.url;
        }
        return await this.uploadImage(file.url);
      });

      return await Promise.all(uploadPromises);
    } catch (error) {
      throw new Error('图片上传失败，请重试');
    }
  },

  // 提交表单
  onSubmit() {
    if (!this.validateForm()) {
      return;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    // 先上传图片
    this.handleImageUpload()
      .then(imageUrls => {
        // 构建提交数据
        const submitData = {
          description: this.data.description,
          type: this.data.typeOptions[this.data.selectedTypeIndex].value,
          images: imageUrls
        };

        // 发送数据到服务器
        wx.request({
          url: 'YOUR_API_DOMAIN/api/v1/questions',
          method: 'POST',
          data: submitData,
          header: {
            'content-type': 'application/json',
            'Authorization': Storage.getAuthToken()
          },
          success: (res) => {
            wx.hideLoading();
            if (res.data.code === 0) {
              this.showSuccessAndBack();
            } else {
              wx.showToast({
                title: res.data.message || '提交失败1',
                icon: 'none',
                duration: 2000
              });
            }
          },fail: (error) => {
            wx.hideLoading();
            wx.showToast({
              title: '提交失败2',
              icon: 'none',
              duration: 2000
            });
          }
        });
      })
      .catch(error => {
        wx.hideLoading();
        wx.showToast({
          title: error.message || '提交失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 显示成功提示并返回
  showSuccessAndBack() {
    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      }
    });
  },

  // 类型选变化
  onTypeChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      selectedTypeIndex: index,
      typeError: ''
    });
  },

  // 修改表单验证方法
  validateForm() {
    let isValid = true;
    
    // 优先验证token
    if (!Storage.getAuthToken()) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      // 如果没有登录，直接返回false，不再验证其他字段
      return false;
    }
    
    // 验证问题描述
    if (!this.data.description.trim()) {
      this.setData({ descriptionError: '请描述您的问题' });
      isValid = false;
    } else if (this.data.description.length < 10) {
      this.setData({ descriptionError: '问题描述至少10个字' });
      isValid = false;
    }
    
    // 验证科室选择
    if (this.data.selectedTypeIndex === -1) {
      this.setData({ typeError: '请选择相关科室' });
      isValid = false;
    }
    
    return isValid;
  },

  // 显示选择器
  onShowPicker() {
    this.setData({ showPicker: true });
  },

  // 确认选择
  onPickerConfirm(e) {
    const { value, label } = e.detail;
    this.setData({
      selectedType: label,
      selectedTypeValue: value,
      showPicker: false,
      typeError: '' // 清除错误提示
    });
  },

  // 取消选择
  onPickerCancel() {
    this.setData({ showPicker: false });
  },

  // 显示类型选择器
  showTypeSelector() {
    this.setData({
      showTypeSelector: true,
      tempSelectedIndex: this.data.selectedTypeIndex || null
    });
  },

  // 选项点击件
  onOptionSelect(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ tempSelectedIndex: index });
  },

  // 确认选择
  onConfirm() {
    if (this.data.tempSelectedIndex !== null) {
      this.setData({
        selectedTypeIndex: this.data.tempSelectedIndex,
        showTypeSelector: false,
        typeError: ''
      });
    }
  },

  // 取消选择
  onCancel() {
    this.setData({ showTypeSelector: false });
  },

  // 弹出层状态变化
  onPopupChange(e) {
    if (!e.detail.visible) {
      this.setData({ showTypeSelector: false });
    }
  },

  // 添加图片
  onAddImage() {
    const that = this;
    const remainCount = 3 - that.data.fileList.length;
    
    if (remainCount <= 0) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: remainCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // 处理选中的图片
        const newFiles = res.tempFiles.map(file => ({
          url: file.path,
          name: file.path.split('/').pop(),
          type: 'image',
          size: file.size
        }));

        // 检查文件大小
        const oversizeFiles = newFiles.filter(file => file.size > 10 * 1024 * 1024);
        if (oversizeFiles.length > 0) {
          wx.showToast({
            title: '图片大小不能超过10MB',
            icon: 'none'
          });
          return;
        }

        // 直接更新文件列表
        that.setData({
          fileList: [...that.data.fileList, ...newFiles]
        });
      }
    });
  },

  // 图片上传成功事件处理
  onUploadSuccess(e) {
    const { files } = e.detail;
    // 保文件列表是数组
    if (!Array.isArray(files)) {
      return;
    }

    // 处理文件信息
    const processedFiles = files.map(file => ({
      url: file.url || file.tempFilePath, // 兼容不同的返回格式
      name: file.name || (file.url || file.tempFilePath).split('/').pop(),
      type: 'image',
      size: file.size,
      fileType: file.fileType || 'image',
      width: file.width,
      height: file.height
    }));

    this.setData({
      fileList: processedFiles,
      imageError: ''
    });
  },

  // 选择图片事件处理
  onSelectImage(e) {
    const { files } = e.detail;
    
    // 检查文件大小
    const oversizeFiles = files.filter(file => file.size > this.data.maxImageSize);
    if (oversizeFiles.length > 0) {
      this.setData({
        imageError: '图片大小不能超过10MB'
      });
      return;
    }

    this.setData({
      imageError: ''
    });
  }
}); 